import { Button, Form } from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import { useState } from 'react';

import styles from './index.module.scss';
import { Input, Picker, SelectButton, FormItem } from '@/components';
import { bindPhoneAndAccount } from '@/utils/login';
import { StorageKey } from '@/constants/storage';
import { DATE_FORMAT } from '@/constants';
import { RouterUtil } from '@/utils';
import { BasicLayout } from '@/layouts';
import { DEFAULT_SHOP_ID } from '@/constants';
import { getApiChoicePersonInfo } from '@/api';
import { useRequest } from '@/hooks';
const Page = () => {
  const _shopId = Taro.getStorageSync(StorageKey.SHOP_ID) || DEFAULT_SHOP_ID;
  const [form] = Form.useForm();
  const [sex, setSex] = useState<string>('女');

  // 从路由参数获取 phone 和 openId
  const params = Taro.getCurrentInstance().router?.params || {};
  const phone = (params.phone as string) || '';
  const openId = (params.openId as string) || '';

  // 获取用户信息
  const { run: fetchUserInfo } = useRequest(getApiChoicePersonInfo, {
    manual: true,
    onSuccess: (res) => {
      if (res) {
        Taro.setStorageSync(StorageKey.USER_INFO, res);
      }
    },
    onError: (error) => {
      console.error('获取用户信息失败', error);
    },
  });

  const handleSubmit = async (values: {
    name: string;
    gender: string;
    marryDate: string;
  }) => {
    try {
      const res = await bindPhoneAndAccount(
        phone,
        openId,
        values.name,
        values.marryDate,
        sex,
      );
      if (res.token) {
        Taro.setStorageSync(StorageKey.TOKEN, res.token);
        // 确保 token 已写入缓存后再获取用户信息（使用 setTimeout 确保在下一个事件循环执行）
        setTimeout(() => {
          // 登录成功后获取用户信息并存入缓存
          fetchUserInfo();
          handleJump();
        }, 0);
      }
    } catch (error) {
      console.error('绑定失败', error);
      Taro.showToast({
        title: '提交失败，请重试',
        icon: 'none',
      });
    }
  };

  const handleJump = () => {
    // 检查是否有保存的返回路径
    const returnPath = Taro.getStorageSync(StorageKey.APP_START_REDIRECT_PATH);
    if (returnPath) {
      // 清除保存的路径
      Taro.removeStorageSync(StorageKey.APP_START_REDIRECT_PATH);
      // 返回到之前的页面（使用 navigateBack 关闭当前页面，返回到详情页）
      // 需要返回两层：完善信息页 -> 登录页 -> 详情页
      Taro.navigateBack({ delta: 2 });
      return;
    }

    // 没有返回路径，使用默认跳转逻辑
    if (!!_shopId) {
      RouterUtil.switchTab('/pages/home/index/index');
    } else {
      RouterUtil.navigateTo('/pages/my/index/index');
    }
  };

  return (
    <BasicLayout className={styles.container} fill transparent loginTip={false}>
      <View className={styles.content}>
        <Form
          form={form}
          onFinish={handleSubmit}
          initialValues={{
            name: '',
            gender: '女士',
            marryDate: '',
          }}
        >
          <View className={styles.form}>
            <FormItem
              label="姓名"
              name="name"
              required
              rules={[{ required: true, message: '请输入姓名' }]}
              labelExtra={
                <SelectButton
                  onChange={(v) => setSex(v as string)}
                  value={sex}
                  options={[
                    { label: '女士', value: '女' },
                    { label: '先生', value: '男' },
                  ]}  
                />
              }
            >
              <Input placeholder="请输入姓名" />
            </FormItem>
            <FormItem label="婚期" name="marryDate">
              <Form.Item name="marryDate" noStyle>
                <Picker.Date
                  type="date"
                  value={form.getFieldValue('marryDate') || undefined}
                  defaultValue={dayjs().format(DATE_FORMAT)}
                  onChange={(v) => form.setFieldsValue({ marryDate: v })}
                />
              </Form.Item>
            </FormItem>
          </View>

          <View className={styles.submit}>
            <Button
              className={styles.btn}
              type="primary"
              size="xlarge"
              block
              onClick={() => form.submit()}
            >
              提交
            </Button>
          </View>
        </Form>
      </View>
    </BasicLayout>
  );
};

export default Page;

